import { ArkcubeScriptParser, FunctionApplyContext, FunctionDeclContext, FunctionDeclStatementContext, ProgramContext } from '../gen/ArkcubeScriptParser';
import { ArkcubeScriptVisitor } from '../gen/ArkcubeScriptVisitor';
import { ArkcubeScriptLexer } from '../gen/ArkcubeScriptLexer';
import * as AntlrUtils from './AntlrUtils';

import { ParseTree } from 'antlr4ts/tree/ParseTree';
import { AbstractParseTreeVisitor } from 'antlr4ts/tree/AbstractParseTreeVisitor'
import { RuleNode } from 'antlr4ts/tree/RuleNode';
import { TerminalNode } from 'antlr4ts/tree/TerminalNode';
import { ErrorNode } from 'antlr4ts/tree/ErrorNode';
import { TokenStreamRewriter } from 'antlr4ts/TokenStreamRewriter';
import { BufferedTokenStream } from 'antlr4ts/BufferedTokenStream';
import { Token } from 'antlr4ts/Token';
import { CharStreams, CommonTokenStream } from 'antlr4ts';

import { FormattingOptions, TextEdit } from 'vscode-languageserver';


export class ArkcubeScriptFormater extends AbstractParseTreeVisitor<string> implements ArkcubeScriptVisitor<string> {

	private readonly space: number;
	private rewriter: TokenStreamRewriter;
	private tokenList: Token[];

	static format(ast: ProgramContext, options: FormattingOptions): TextEdit[] {
		return [];
	}
	static formatAsString(expression: string, space: number): string {
		const charStream = CharStreams.fromString(expression);
		const lexer = new ArkcubeScriptLexer(charStream);
		const tokenStream = new CommonTokenStream(lexer);
		const parser = new ArkcubeScriptParser(tokenStream);
		const prog = parser.program();

		const formatter = new ArkcubeScriptFormater(tokenStream, space);
		formatter.visit(prog);
		return formatter.getFormattedString();
	}

	constructor(tokens: BufferedTokenStream, space: number) {
		super();
		this.space = space === null || space < 1 ? 1 : space;
		this.rewriter = new TokenStreamRewriter(tokens);
		this.tokenList = AntlrUtils.tokenStreamToList(tokens);
	}

	visitFunctionDeclStatement(ctx: FunctionDeclStatementContext) {
		if(ctx.children) {
			ctx.children.forEach(child => {
				this.visit(child);
			});
		}
		return "";
	}
	getFormattedString(): string {
		return this.rewriter.getText();
	}

	protected defaultResult(): string {
		return '';
	}
}



